#!/usr/bin/env python
'''
A set of useful function that performs operations on
the images used accross the program
'''

import gtk
import Image
import Misc
import os
import tempfile

def scale_stream(data, height=60):
    '''
    Take a data image stream in input, scale it to the desidered
    height, and gives back a gtk.gdk.Pixbuf
    '''

    # we need a pixbuf loader in place of a pixbuf
    # because we don't have a file on filesystem
    # but we have to retrieve the datas from the
    # the database instead
    newimg = gtk.gdk.PixbufLoader()
    newimg.write(data)
    newimg.close()
    newimg = newimg.get_pixbuf()

    w = newimg.get_width()
    h = newimg.get_height()

    # if less than specified, don't do anything
    if (h > height):
        # scale it with interpolation:
        # current-height:current-width = new-height:new-width

        ret = newimg.scale_simple((w * height) / h, height, gtk.gdk.INTERP_BILINEAR)
    else:
        ret = newimg

    return ret

def convertRawStreamToPixbuf(data):
    '''Convert a raw data stream (image) to a gtk.gdk.Pixbuf'''

    if (data == None):
        return None

    newimg = gtk.gdk.PixbufLoader()
    newimg.write(data)
    newimg.close()
    newimg = newimg.get_pixbuf()
    return newimg

def resizeFile(filename, maxsize):
    '''
    Take 'filename' and resize it to maxsize x maxsize (but keeping
    the aspect ratio)

    Returns the path to the newly written file (must be destroyed
    after use).
    '''

    curr_image = Image.open(filename)
    newfile = False

    curr_w, curr_h = curr_image.size
    if ((curr_w > maxsize) or (curr_h > maxsize)):
        # use .thumbnail in place of .resize, so we keep the width/height
        # aspect ratio
        curr_image.thumbnail((maxsize, maxsize), Image.BILINEAR)

        # use the tmp image (it is located under /tmp/[nameoftheoldfile]
        tmpdir = tempfile.gettempdir()
        filename = tmpdir + os.path.sep + os.path.split(filename)[1]
        curr_image.save(filename)
        newfile = True

    return filename, newfile
